package com.yenlien.traceyun.business.controller;

import com.yenlien.traceyun.business.entity.Grade;
import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import com.yenlien.traceyun.business.service.GradeService;
import com.yenlien.traceyun.webase.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LiuSha on 2020/7/27.
 */
@RestController
@RequestMapping("/grade")
public class GradeController extends BaseController {
    @Autowired
    private GradeService gradeService;

    @RequestMapping(value = "/findByList", method = RequestMethod.POST)
    public Object findByList(@RequestBody Grade grade) {
        grade.setCompanyId(UserAuthUtil.getLoginUser().getCompanyId());
        return buildPage(gradeService.findByList(grade));
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Object save(Grade grade, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        grade.setCompanyId(UserAuthUtil.getLoginUser().getCompanyId());
        gradeService.save(grade, files);
        return success("success");
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object update(Grade grade, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        gradeService.update(grade, files);
        return success("success");
    }

    @RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
    public Object findById(@PathVariable String id) {
        return success(gradeService.findById(id));
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public Object delete(@PathVariable String id) {
        gradeService.delete(id);
        return success("success");
    }
}
